<?php

/**
 * Auth controller
 *
 * Auth controller in application
 *
 * PHP Version: 1.2.3
 *
 * @author Johari <joharijumali@gmail.com>
 */

/**
 * Auth class
 *
 * Auth class
 *
 * @author Johari <joharijumali@gmail.com>
 */

class Console_Auth_Controller extends Base_Controller
{

    // public $restful = false;

    /**
     * Function action_authenticate
	 *
	 * @return action_authenticate.
     */
    public function action_authenticate()
    {
        $input = Input::all();
        
        $rules = array(
            'su_username' => 'required|email|exists:sys_user',
            'su_password' => 'required'
        );
        
        $validation = Validator::make($input, $rules);
        
        if ($validation->fails()) {
            return Redirect::to('home')->with_errors($validation);
        }
        
        $credentials = array(
            'username' => $input['su_username'],
            'password' => $input['su_password'],
            'su_status' => 'Aktif'
        );
        
        $notallowed = array(
            'username' => $input['su_username'],
            'password' => $input['su_password'],
            'su_status' => 'Gantung'
        );	

		$expired = array(
            'username' => $input['su_username'],
            'password' => $input['su_password'],
            'su_status' => 'Tamat Perkhidmatan'
        );

        if (Auth::attempt($credentials)) {

            $isAdmin = Console_Role::where('sur_id','=',Auth::user()->sur_id)->where('sur_admin','=',1)->first();

            if($isAdmin):
                return Redirect::to('home/dashboard');
            else:
                return Redirect::to('home/dashboard');
            endif;
            
        } else if(Auth::attempt($notallowed)) {
            Session::flash('login_notaccess', 'You not allowed to access the system.');
            return Redirect::to(URL::base());

        } else if(Auth::attempt($expired)) {
			Session::flash('login_notaccess', 'You not allowed to access the system.');
            return Redirect::to(URL::base());

		} else {
            Session::flash('login_errors', 'Maaf, E-mel atau Kata Laluan anda tidak betul.');
            return Redirect::to(URL::base());
        }
        // }		
    }
	
	/**
     * Function action_verifyupdate
	 *
	 * @return action_verifyupdate.
     */
    public function action_verifyupdate()
	{
        $input = Input::all();

        $rules = array(
            'su_password' => 'required|between:6,12'
        );
        
        $validation = Validator::make($input, $rules);
		
		if ($validation->fails()) {
            Session::flash('login_errors', 'Maaf, Kata Laluan Baru perlu antara 6-12 huruf.');
            return Redirect::to('confirmation/'.$input['key'])->with_errors($validation);
        }

        $existedUser = Console_User::where('su_validationkey', '=', $input['key'])
        ->where('su_status', '=', 'Pengesahan')
        ->or_where('su_status', '=', 3)
        ->first(array('su_id'));

        if ($existedUser) {
		
            $result = Console_User::confirmUser($input, $existedUser->su_id);
			
			if($result):
				
                $profile = Console_Profile::where('su_id', '=', $existedUser->su_id)->first(array('sup_emel'));

				$credentials = array(
					'username' => $profile->sup_emel,
					'password' => $input['su_password']
				);

				if (Auth::attempt($credentials)) {

					$isAdmin = Console_Role::where('sur_id','=',Auth::user()->sur_id)->where('sur_admin','=',1)->first();
					if($isAdmin):
						return Redirect::to('home/dashboard');
					else:
						return Redirect::to('home/dashboard');
					endif;

                    try {
                            $mailer = Message::to($profile->sup_emel);
                            $mailer->from('admin@gmail.com', __('admin.subjectinfo'));
                            $mailer->subject(Str::title(__('admin.subjectinfo')));
                            $mailer->body('view: admin::plugin.emailacc');
                            $mailer->body->username = $profile->sup_emel;
                            $mailer->body->password = $input['su_password'];
                            $mailer->body->name = $profile->sup_name;
                            $mailer->body->key = $input['key'];
                            $mailer->html(true);
                            $mailer->send();
                        } catch (Exception $e) {
                            Log::write('email', 'Message was not sent.');
                            Log::write('email', 'Mailer error: '.$e->getMessage());
                        }


				} else {
					Session::flash('login_errors', 'Maaf, E-mel atau Kata Laluan anda tidak betul.');
					return Redirect::to(URL::base());
				}				
				
				
			endif;
			
        } else {
            return Redirect::to('confirmation/'.$input['key']);
        }
        
    }
	
	/**
     * Function action_logout
	 *
	 * @return action_logout.
     */
    public function action_logout()
    {
        Auth::logout();
        return Redirect::to(URL::base());		
    }
			
	/**
     * Function action_forgot
	 *
	 * @return action_forgot.
     */
    public function action_forgot()
	{
        $rules = array(
                'emel'  => 'required|exists:sys_user_profile,sup_emel'
        );

        $validation = Validator::make(Input::all(), $rules);

        if ($validation->fails()) {
            return Redirect::to('home/forgot')->with_errors($validation);
        }

        $validatekey = Str::random(32, 'alpha');

        $emel = Input::get('emel');
        $pword = Str::random(16, 'alpha');

        $profile = Console_Profile::where('sup_emel', '=', $emel)->first();

        if ($profile) {
            try {
                $user = Console_User::find($profile->su_id);

                $user->su_password = $pword;
                $user->su_status = 3;
                $user->su_validationkey = $validatekey;
                $user->save();

                Log::write('User', 'Reset Login User '.$profile->sup_no_ic.' Via forgot password');
            } catch (Exception $e) {
                Log::write('User', 'Reset Login User '.$profile->sup_no_ic.' failed!!!');
                Log::write('User', 'Mailer error: '.$e->getMessage());
            }
        }

        try {
            $mailer = Message::to($profile->sup_emel);
            $mailer->from('admin@3fresources.com', __('global.sysname'));
            $mailer->subject(Str::title(__('admin.subjectreset')));
            $mailer->body('view: admin::plugin.emailaccreset');
            $mailer->body->username = $profile->sup_emel;
            $mailer->body->name = $profile->sup_nama;
            $mailer->body->password = $pword;
            $mailer->body->key = $validatekey;
            $mailer->html(true);
            $mailer->send();
        } catch (Exception $e) {
            Log::write('email', 'Message was to '.$profile->sup_emel.' not sent.');
            Log::write('email', 'Mailer error: '.$e->getMessage());
        }

        return Redirect::to('home/forgot')->with('status_success', 'Kemaskini Kata Laluan Berjaya. E-mel Pengesahan Telah Dihantar Ke '.$emel);
    }

}

?>